// pages/jinEweiSalesperson/jinEweiSalesperson.js
var app=getApp()
var util=require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    complete:0,
    data:'',
    line:'\n'
  },
  withdrawShowModal(e) {
    this.setData({
      modalName: 'withdraw'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideHomeButton();
    var that=this;
    if(options){
      if(options.q){
        let pr=options.q;
        let lr=pr.substring(pr.length-1,pr.length).toUpperCase();
        that.setData({
          lr:lr
        })
      }
    }else{
      that.setData({
        lr:'V'
      })
    }
    
    if (wx.getStorageSync('openid')) {
      let openid = wx.getStorageSync('openid')
      that.seek(openid)
    } else {
      wx.cloud.callFunction({
        name: 'login',
      }).then(res => {
        let openid = res.result.openid;
        that.seek(openid)
      })
    }
  },
  toSetting(e) {
    wx.navigateTo({
      url: '../jinEweiSalespersonEntry/jinEweiSalespersonEntry?data=' + JSON.stringify(this.data.data),
    })
  },
  seek: function (openid) {
    var that = this;
    util.request('/sales/detail', {
      openid: openid,
      suffix: '_e'
    }, 'GET').then(res => {
      console.log(res)
      let data = res.data;
      if (data.length == 0) {
        let type = "regisiter";
        wx.redirectTo({
          url: '../jinEweiSalespersonEntry/jinEweiSalespersonEntry?type=' + type + '&lr=' + that.data.lr,
        })
      } else {
        let userInfo = wx.getStorageSync('userInfo')
        that.setData({
          nickName: userInfo.nickName,
          data: data[0],
          avatarUrl: userInfo.avatarUrl,
          income: data[0].income,
          balance: data[0].remaining,
          withdrawal:data[0].withdrawal
        })
        let date = util.formatDate(new Date())
        util.request('/order/count', {
          openid: openid,
          date: date.substring(0, 7),
          brand_code:that.data.lr
        }, 'GET').then(res => {
          console.log(res.data)
          that.setData({
            dealNum: res.data[0].reach,
            turnover: res.data[0].profit
          })
        })
        util.request('/order/count', {
          openid: openid,
          brand_code: that.data.lr
        }, 'GET').then(res => {
          console.log(res.data)
          that.setData({
            reach: res.data[0].reach,
          })
        })
        util.request('/withdrawal/count', {
          openid: openid,
          date: date.substring(0, 7),
          brand_code: that.data.lr
        }, 'GET').then(res => {
          console.log(res.data)
          that.setData({
            account: res.data[0].total,
          })
        })
        that.setData({
          complete:1,
          loading:false
        })
        util.request('/withdrawal/remind',{
          openid: openid
        },'POST').then(res=>{
          if(res.data=='need'){
            that.setData({
              modalName:'remind'
            })
          }
        })
      }
    })
  },
  withdrawal: function () {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['5J1Vm_GHvcTOS57iC52BM12ave8-mI1Mx9zl6iDghpI'],
      success(res) {
        console.log(res)
        if (JSON.stringify(res).indexOf('accept') !== -1) {
          if (that.data.balance == 0) {
            wx.showToast({
              title: '暂无余额可提现',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showLoading()
            util.request('/withdrawal/insert', {
              openid: app.globalData.openid,
              status: 'waiting',
              suffix: '_e',
              fee: that.data.balance,
              creation_timestamp: Date.parse(util.formatTime(new Date()).replace(/-/g, '/')) / 1000
            }, 'POST').then(res => {
              console.log(res)
              if (res.data == 'repeat') {
                wx.hideLoading()
                wx.showModal({
                  title: '请勿重复申请，耐心等待！',
                  showCancel:false
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '提交成功',
                  icon: 'success',
                  duration: 1000
                })
                that.setData({
                  modalName: null
                })
                setTimeout(() => {
                  wx.showModal({
                    title: '提现申请已提交',
                    showCancel: false,
                    content: '工作人员将在3个工作日内打款，请耐心等待'
                  })
                }, 1000)
              }
            })
          }
        }
      },
      fail(res) {
        // 20004:用户关闭了主开关 或在 消息通知 里 “拒绝接收”操作，无法进行订阅,引导开启
        if (res.errCode == 20004) {
          console.log(res, 'fail:用户关闭了主开关，无法进行订阅,引导开启---');
          wx.showModal({
            title:'未开启提现成功通知，请确认是否已开启【接收订阅消息】，允许通知提现成功通知。',
            success:function(res){
              if(res.confirm){
                wx.openSetting({
                  withSubscriptions: true,
                })
              }
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(wx.getStorageSync('refresh')){
      this.onLoad()
      wx.removeStorageSync('refresh')
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})